package com.j4dream.time;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

public class timeTest {

	@Test
	public void 计算时间差天数() {
		// 自然日通俗的讲就是指一天24小时
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d1 = df.parse("2004-08-03 13:31:40");
			Date d2 = df.parse("2004-01-02 11:30:24");
			long diff = d1.getTime() - d2.getTime();
			long days = diff / (1000 * 60 * 60 * 24);
			System.out.println(days);
		} catch (Exception e) {
		}
	}

	@Test
	public void 计算日期差_天_时_分_秒_1() throws ParseException {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date now = df.parse("2004-03-26 13:31:40");
		java.util.Date date = df.parse("2004-01-02 11:30:24");
		long between = now.getTime() - date.getTime();
		long day = between / (24 * 60 * 60 * 1000);
		long hour = (between / (60 * 60 * 1000) - day * 24);
		long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		System.out.println("" + day + "天" + hour + "小时" + min + "分" + s + "秒");
	}

	@Test
	public void 计算日期差_天_时_分_秒_2() throws ParseException {
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date begin = dfs.parse("2004-01-02 11:30:24");
		java.util.Date end = dfs.parse("2004-03-26 13:31:40");
		long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒
		long day1 = between / (24 * 60 * 60);
		long hour1 = between % (24 * 60 * 60) / (60 * 60);
		long minute1 = between % (60 * 60) / 60;
		long second1 = between % 60;
		System.out.println("" + day1 + "天" + hour1 + "小时" + minute1 + "分" + second1 + "秒");
	}
	@Test
	public void 比较时间大小() {
		String s1 = "2008-01-25 09:12:09";
		String s2 = "2008-01-29 09:12:11";
		java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Calendar c1 = java.util.Calendar.getInstance();
		java.util.Calendar c2 = java.util.Calendar.getInstance();
		try {
			c1.setTime(df.parse(s1));
			c2.setTime(df.parse(s2));
		} catch (java.text.ParseException e) {
			System.err.println("格式不正确");
		}
		int result = c1.compareTo(c2);
		if (result == 0)
			System.out.println("c1相等c2");
		else if (result < 0)
			System.out.println("c1小于c2");
		else
			System.out.println("c1大于c2");
	}
}
